# -*- coding: utf-8 -*-
import datetime
import random
import threading

from info.api.ZTCCLOUD import ZTCCLOUD
from info.utils import utils
from utils import dbUtils


class BaseData(ZTCCLOUD):

    # 创建公司部门岗位员工
    def create_comp_dept(self, **kwargs):
        """
        创建公司部门岗位员工
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建公司部门岗位员工"
        msg = ""
        try:
            numdas = 1
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_comp, num_dept, num_post, num_emp = abs(int(r_num[0])), abs(int(r_num[1])), abs(int(r_num[2])), \
                                                        abs(int(r_num[3]))  # 公司、部门、岗位、员工数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                root = 0
            except:
                return f"{method_name} 获取执行次数异常"
            if num_comp <= 0:
                return f"{method_name} 执行次数必须大于0"
            comp_num = int(self.random_character(length='5'))  # 公司级随机数
            num_thistest = 0  # 岗位计数器

            # 公司部分
            dType = 0  # 公司
            if not root:
                pid_c = self.QUERY_DEPT_FINDCHILDRENBYIDANDVALIDITY(base_url, cookie)  # 集团id
            else:
                root_list = str(root).split('/')
                result = self.QUERY_DEPT_FINDPARENTBYNAMEANDVALIDITY(base_url, cookie, name=root_list[0])  # 公司的pid
                pid_c = self.GET_DICT(result, 'id', name=root)

                if not pid_c:
                    return "创建公司部门岗位员工 未找到父节点"
            deptFid = f'/{pid_c} ^ 4'
            companyId_list = []  # 公司id列表
            level_c = 1
            for num_c in range(1, num_comp + 1):

                companyCode = f"{namedFlag}companyCode{str(comp_num)}_{str(num_c)}"
                companyName = f"{namedFlag}companyName{str(comp_num)}_{str(num_c)}"
                result = self.ADD_COMMON_DEPT(base_url, cookie, dType, companyCode, companyName, f'LV{str(level_c)}',
                                              pid_c,
                                              deptFid)
                while '级别配置有误' in result.get('msg'):
                    level_c += 1
                    result = self.ADD_COMMON_DEPT(base_url, cookie, dType, companyCode, companyName,
                                                  f'LV{str(level_c)}',
                                                  pid_c, deptFid)
                    if result.get('msg') == "success" or level_c > 10:
                        break

                id = self.GET_DICT(result, 'id')
                if id:
                    companyId_list.append(id)
                    if num_dept <= 0:
                        numdas += 1
                        utils.set_cache(base_url, user_addr, utils.get_func_name())

            permanentLand_temp = self.QUERY_CITY_INFO(base_url, cookie)

            # 部门部分
            # deptId_list = []
            dType = 1  # 部门
            level_d = 1
            dept_num = int(self.random_character(length='5'))  # 部门级随机数
            postId_temp = ""  # 缓存一次岗位id，用于下一个岗位员工的兼岗

            for index, pid in enumerate(companyId_list):
                for num_d in range(1, num_dept + 1):
                    deptFid = f'/{pid_c}^4/{pid}^0'
                    deptName = f"{namedFlag}部门名称{str(comp_num)}_{str(num_d)}"
                    deptCode = f"{namedFlag}deptCode{str(comp_num)}_{str(num_d)}"
                    result = self.ADD_COMMON_DEPT(base_url, cookie, dType, deptCode, deptName, f'LV{str(level_d)}', pid,
                                                  deptFid)
                    while '级别配置有误' in result.get('msg'):
                        level_c += 1
                        result = self.ADD_COMMON_DEPT(base_url, cookie, dType, deptCode, deptName, f'LV{str(level_d)}',
                                                      pid,
                                                      deptFid)
                        if result.get('msg') == "success" or level_d < 10:
                            break
                    deptId = self.GET_DICT(result, 'id')
                    if not num_post:
                        numdas += 1
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        # break

                    # 岗位部分
                    pType = 2  # 岗位
                    level_p = 1
                    post_num = int(self.random_character(length='5'))  # 岗位级随机数
                    for num_p in range(1, num_post + 1):
                        postFid = f"/{pid_c}^4/{pid}^0/{deptId}^1/"
                        postName = f"{namedFlag}岗位名称{str(dept_num)}_{str(num_p)}"
                        postCode = f"{namedFlag}postCode{str(dept_num)}_{str(num_p)}"
                        result = self.ADD_COMMON_DEPT(base_url, cookie, pType, postCode, postName, f'LV{str(level_p)}',
                                                      deptId,
                                                      postFid)
                        while '级别配置有误' in result.get('msg'):
                            level_p += 1
                            result = self.ADD_COMMON_DEPT(base_url, cookie, pType, postCode, postName,
                                                          f'LV{str(level_p)}',
                                                          pid, postFid)
                            if result.get('msg') == "success" or level_p < 10:
                                break
                        if not num_emp:
                            numdas += 1
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            # break
                        postId = self.GET_DICT(result, 'id')  # 岗位id

                        for num_e in range(1, num_emp + 1):
                            empName = f"{namedFlag}员工名称{str(post_num)}_{str(num_e)}"
                            empCode = f"{namedFlag}empCode{str(post_num)}_{str(num_e)}"
                            result = self.ADD_COMMON_EMP(base_url, cookie, empNo=empCode, realName_zh_CN=empName,
                                                         permanentLand=permanentLand_temp, mainPost=postId,
                                                         haveAccount='Y',
                                                         companyId=pid,
                                                         accessoryPost=[postId_temp] if postId_temp else [])
                            if result.get('msg') == 'success':
                                numdas += 1
                                utils.set_cache(base_url, user_addr, utils.get_func_name())

                        postId_temp = postId  # 缓存一次岗位id，用于下一个岗位员工的兼岗

                        post_num += 1
                    dept_num += 1
                comp_num += 1

            return "success..."
        except Exception as e:
            return f"{msg}\n{str(e)}"

    # 创建客商及客商科目分配
    def create_vendors(self, **kwargs):
        """
        创建客商及客商科目分配
        confList：配置文件对象，dict
        value：界面值
        base_url：基础url
        kwargs: namedflag每笔数据的标记；
        """
        msg = ""
        try:
            cookie = kwargs.get("cookie")
            base_url = kwargs.get("server_addr")
            user_addr = kwargs.get("user_addr")
            r_num = kwargs.get("run_num").strip("^").split("^")
            if len(r_num) == 1:
                r_num.append(0)
            elif len(r_num) <= 0:
                r_num = [0] * 2
            num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建客商数和每个客商关联科目数
            namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
        except:
            return "创建客商  获取执行次数异常"
        if num_makeing <= 0:
            return "创建客商  执行次数必须大于0"
        bankList = self.FINDDATAS_SplitWord(base_url, cookie, limit=5)
        # 获取核算主体列表
        result09 = {}
        if num2_makeing:
            result09 = self.FINDDATA(base_url, cookie,
                                     f'page=1&limit={num2_makeing * 2}&orderField=&order=&lovKey=sysFuLeMode.findNameAndCode&SOB_ID=')

        leId_list = self.GET_VALUE_FROM_JSON_DICT(result09, 'ID')
        coaSchemeId_list = self.GET_VALUE_FROM_JSON_DICT(result09, 'COA_SCHEME_ID')
        leId_coaId_list = [list(k) for k in zip(leId_list, coaSchemeId_list)]
        if len(leId_list) < num2_makeing:
            return '创建客商  测试环境核算主体数量至少应比每个客商分配科目的数量多'
        numdas, numdas2 = 1, 1
        for num_v in range(1, num_makeing + 1):
            leId_coaId_list = random.sample(leId_coaId_list, k=num2_makeing)
            leId_list_choiced = [i[0] for i in leId_coaId_list]
            coaSchemeId_list_choiced = [i[1] for i in leId_coaId_list]

            random_num = f'{random.randint(int(1e+9), int(1e+10))}'  # 随机数10位
            vendorCode = f"{namedFlag}{str(random_num)}"
            vendorName = f"{namedFlag}客商名称{str(random_num)}"
            taxNumber = f"{namedFlag}taxNum{str(random_num)}_{str(num_v)}"
            # 是否全局客商
            globalVendor = str(random.randint(0, 1))
            result = self.ADD_VENDORS(base_url, cookie, vendorCode, vendorName, taxNumber,
                                      data=random.choice(bankList), globalVendor=globalVendor,
                                      vendorsCompany=leId_list_choiced)
            if result.get("msg") != "success":
                return f"创建客商失败  已完成【{numdas}】次\n接口响应：{result}"
            elif result.get("msg") == "字段长度超过限制":
                return "字段长度超出限制，请控制下长度[末尾特征标记]"
            elif result.get('msg') == 'success':
                if not num2_makeing:
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                vendorId = self.GET_DICT(self.SIMPLE_QUERY_VENDORS(base_url, cookie, vendorCode=vendorCode), 'id')
                for key, leId in enumerate(leId_list_choiced):  # 如果num2_makeing是0，就不会进
                    accountList = self.GET_COAINFO_MUST(base_url, cookie, coaSchemeId=coaSchemeId_list_choiced[key])
                    k = random.randint(0, len(accountList) - 1)
                    if globalVendor == '0':  # 如果是全局
                        resultoo = self.ADD_VENDORSCOMPANY(base_url, cookie, leId=leId, accountId=accountList[k][0],
                                                           accountErpCode=accountList[k][2],
                                                           accountErpName=accountList[k][1], vendorId=vendorId)
                    else:
                        resultr = self.QUERY_VENDORSCOMPANY(base_url, cookie, vendorId=vendorId, flagValid='0',
                                                            leId=leId)
                        Id = self.GET_DICT(resultr, 'id')
                        initRowIndex = self.GET_DICT(resultr, 'initRowIndex')
                        resultoo = self.ADD_VENDORSCOMPANY(base_url, cookie, leId=leId, accountId=accountList[k][0],
                                                           accountErpCode=accountList[k][2],
                                                           accountErpName=accountList[k][1],
                                                           vendorId=vendorId, id=Id, initRowIndex=initRowIndex,
                                                           post='put')
                    if resultoo.get('msg') == 'success':
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas2 += 1
                    else:
                        msg_ = resultoo.get('msg')
                        if msg_:
                            msg += msg_ + '\n'
        numdas += 1
        if numdas >= num_makeing:
            msg = f"客商创建完成，共【{numdas - 1}】条"
        else:
            dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
            msg = f"客商创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
        return msg

    # 创建临时供应商
    def create_temp_vendors(self, **kwargs):
        """
        创建临时供应商
        kwargs: namedflag每笔数据的标记；
        """
        try:
            cookie = kwargs.get("cookie")
            base_url = kwargs.get("server_addr")
            user_addr = kwargs.get("user_addr")
            num_makeing = int(kwargs.get('run_num') if kwargs.get('run_num') else 0)  # 创建临时客商数
            namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
        except:
            return "创建临时供应商  获取执行次数异常"
        if num_makeing <= 0:
            return "创建临时供应商  执行次数必须大于0"
        bankList = self.FINDDATAS_SplitWord(base_url, cookie, limit=5)
        numdas = 1
        vendors_fs = int(self.random_character(length='5'))  # 高并发专用随机数
        for num_v in range(1, num_makeing + 1):
            random_num = f'{random.randint(int(1e+9), int(1e+10))}'  # 随机数10位
            bankAccountName = f"{namedFlag}{str(random_num)}_{vendors_fs}"
            if namedFlag:
                vendorName = f"{namedFlag}临时供应商{str(random_num)}"
            else:
                vendorName = f"临时供应商{str(random_num)}"
            bankAccount = f"{namedFlag}bankAccount{str(random_num)}"
            result = self.ADD_TEMP_VENDORS(base_url, cookie, vendorName, bankAccountName, bankAccount,
                                           data=bankList[random.randint(0, len(bankList) - 1)])
            if result.get("msg") != "success":
                return f"创建临时供应商失败  已完成【{numdas}】次\n接口响应：{result}"
            utils.set_cache(base_url, user_addr, utils.get_func_name())
            numdas += 1
        if numdas >= num_makeing:
            msg = f"临时供应商创建完成，共【{numdas - 1}】条"
        else:
            dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
            msg = f"临时供应商创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
        return msg

    # 创建项目
    def create_project(self, **kwargs):
        """
        创建项目
        kwargs: namedflag每笔数据的标记；
        """
        try:
            cookie = kwargs.get("cookie")
            base_url = kwargs.get("server_addr")
            user_addr = kwargs.get("user_addr")
            num_makeing = int(kwargs.get('run_num') if kwargs.get('run_num') else 0)  # 创建客商数
            namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
        except:
            return "创建项目  获取执行次数异常"
        if num_makeing <= 0:
            return "创建项目  执行次数必须大于0"
        bankList = self.FINDDATAS_RoleMode(base_url, cookie, limit=10)
        bankList = self.GET_VALUE_FROM_JSON_DICT(bankList, "ID")

        fuList = self.FINDDATAS_FuLeMulti(base_url, cookie, limit=10)
        fuList = self.GET_VALUE_FROM_JSON_DICT(fuList, "ID")

        numdas = 1
        for num_v in range(1, num_makeing + 1):
            random_num = f'{random.randint(int(1e+9), int(1e+10))}'  # 随机数10位
            project_code = f"{namedFlag}{str(random_num)}"
            if namedFlag:
                project_name = f"{namedFlag}项目名称{str(random_num)}"
            else:
                project_name = f"项目名称{str(random_num)}"
            result = self.ADD_PROJECT(base_url, cookie, project_code.replace("_", ""), project_name.replace("_", ""),
                                      principals=bankList[random.randint(1, len(bankList) - 1)],
                                      directors=bankList[random.randint(1, len(bankList) - 1)],
                                      fuId=fuList[random.randint(0, len(bankList) - 1)])
            if result.get("msg") != "success":
                return f"创建项目失败  已完成【{numdas}】次\n接口响应：{result}"
            utils.set_cache(base_url, user_addr, utils.get_func_name())
            numdas += 1
        if numdas >= num_makeing:
            msg = f"项目创建完成，共【{numdas - 1}】条"
        else:
            dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
            msg = f"项目创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
        return msg

    # 创建维度
    def create_flexvaluesets(self, **kwargs):
        """
        创建维度和成员
        base_url：基础url
        kwargs: namedflag每笔数据的标记；
        """
        msg = ''
        num_test_1, num_test_2 = 1, 1

        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建维度数和成员数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建维度和成员  创建维度 获取执行次数异常"
            if num_makeing <= 0:
                return "创建维度和成员  创建维度 执行次数必须大于0"
            numdas = 1
            code_list = []
            for num_v in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数10位
                this_code = f"{namedFlag}flex^_^{str(random_num)}"
                if namedFlag:
                    this_name = f"{namedFlag}维度名称{str(random_num)}"
                else:
                    this_name = f"维度名称{str(random_num)}"
                while True:
                    result = self.ADD_FLEXVALUESETS(base_url, cookie, this_code, this_name)
                    if result.get("msg") != "success":
                        if num_test_1 < 3:
                            num_test_1 += 1
                            continue
                        else:
                            msg_this = result.get('msg')
                            if msg_this:
                                msg += msg_this + '\n'
                                break
                    else:
                        code_list.append(this_code)
                        break
                if num_test_1 >= 3:
                    break
                if num2_makeing == 0:
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
            if num2_makeing <= 0:
                return "创建维度和成员  创建成员 执行次数小于等于0，不执行"
            for code in code_list:
                list_id = self.QUERY_FLEXVALUESETS(base_url, cookie, keyword=code)
                if not len(list_id):
                    return f"创建维度和成员  创建成员 未查询到编码为【{code}】的维度信息，请在对应服务器确认功能是否正常"
                for ss in range(1, num2_makeing + 1):
                    random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数10位
                    this_code = f"{namedFlag}flex-_-{str(random_num)}"
                    if namedFlag:
                        this_name = f"{namedFlag}维度成员名称{str(random_num)}"
                    else:
                        this_name = f"维度成员名称{str(random_num)}"
                    result = self.ADD_FLEXVALUESETS_CUSTOM(base_url, cookie, this_code, this_name, list_id[0])
                    if result.get("msg") != "success":
                        return f"创建维度和成员  创建成员失败 已完成【{numdas}】次\n接口响应：{result}"
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
            totalNums = 1
            for n in [num_makeing, num2_makeing]:
                if n > 0:
                    totalNums *= n
                else:
                    break
            if numdas > totalNums:
                msg = f"维度创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"维度创建未完成，已完成【{numdas - 1}】条，未完成【{totalNums - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return str(e)

    # 创建科目体系
    def create_coaaccountscheme(self, **kwargs):
        """
        创建科目体系及体系下的会计科目
        kwargs: namedflag每笔数据的标记；
        """
        msg = ''
        num_test_1, num_test_2 = 1, 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 2:
                    r_num.append(0)
                num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建科目体系数,会计科目数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建科目体系及体系下的会计科目  创建科目体系 获取执行次数异常"
            if num_makeing <= 0:
                return "创建科目体系及体系下的会计科目  创建科目体系 执行次数必须大于0"
            numdas = 1
            code_list = []
            for num_v in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数10位
                this_code = f"{namedFlag}scheme{str(random_num)}"
                if namedFlag:
                    this_name = f"{namedFlag}科目名称{str(random_num)}"
                else:
                    this_name = f"科目名称{str(random_num)}"
                while True:
                    result = self.ADD_SCHEME(base_url, cookie, this_code, this_name)
                    if result.get("msg") != "success":
                        if num_test_1 < 3:
                            num_test_1 += 1
                            continue
                        else:
                            msg_this = result.get('msg')
                            if msg_this:
                                msg += msg_this + '\n'
                                break
                    else:
                        code_list.append(this_code)
                        break

                if num_test_1 >= 3:
                    break
                if num2_makeing == 0:
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
            if num2_makeing <= 0:
                return "创建科目体系及体系下的会计科目  创建会计科目 执行次数小于等于0，不执行"
            for code in code_list:
                list_id = self.QUERY_SCHEME(base_url, cookie, keyword=code)
                if not len(list_id):
                    return f"创建科目体系及体系下的会计科目  创建会计科目 未查询到编码为【{code}】的维度信息，请在对应服务器确认功能是否正常"
                for ss in range(1, num2_makeing + 1):
                    random_num = f'{random.randint(int(1e+9), int(1e+10))}'  # 随机数10位
                    this_code = f"{namedFlag}Coa{str(random_num)}"
                    if namedFlag:
                        this_name = f"{namedFlag}会计科目名称{str(random_num)}"
                    else:
                        this_name = f"会计科目名称{str(random_num)}"
                    result = self.ADD_COA(base_url, cookie, this_code, this_name, list_id[0])
                    if result.get("msg") != "success":
                        return f"创建科目体系及体系下的会计科目  创建会计科目失败 已完成【{numdas}】次\n接口响应：{result}"
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
            totalNums = 1
            for n in [num_makeing, num2_makeing]:
                if n > 0:
                    totalNums *= n
                else:
                    break
            if numdas > totalNums:
                msg = f"科目体系及体系下的会计科目创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"科目体系及体系下的会计科目创建未完成，已完成【{numdas - 1}】条，未完成【{totalNums - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return str(e) + "\n" + msg

    # 创建汇率方案
    def create_exchangerate(self, **kwargs):
        """
        创建汇率方案及下属的汇率
        kwargs: namedflag每笔数据的标记；
        """
        msg = ""
        num_test_1, num_test_2 = 1, 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 2:
                    r_num.append(0)
                num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建汇率方案数, 汇率数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建汇率方案及下属的汇率  创建汇率方案 获取执行次数异常"
            if num_makeing <= 0:
                return "创建汇率方案及下属的汇率  创建汇率方案 执行次数必须大于0"
            result1 = self.FINDDATA(base_url, cookie,
                                    data='page=1&limit=50&orderField=&order=&lovKey=sysCurrencyMode.findNameAndCodeSingle&hasCount=N')
            dictCode_list = self.GET_VALUE_FROM_JSON_DICT(result1, 'ID')  # 币种列表
            CURRENCY_CODE_list = self.GET_VALUE_FROM_JSON_DICT(result1, 'CURRENCY_CODE')  # 币种列表
            numdas = 1
            code_list = []
            for num_v in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                this_code = f"{namedFlag}rate{str(random_num)}"
                if namedFlag:
                    this_name = f"{namedFlag}汇率方案名称{str(random_num)}"
                else:
                    this_name = f"汇率方案名称{str(random_num)}"
                # 挑一个币种
                curr_id = dictCode_list[random.randint(0, len(dictCode_list) - 1)]
                while True:
                    result = self.ADD_EXCHANGERATE(base_url, cookie, this_code, this_name, curr_id)
                    if result.get("msg") != "success":
                        if num_test_1 < 3:
                            num_test_1 += 1
                            continue
                        else:
                            msg_this = result.get("msg")
                            if msg_this:
                                msg += msg_this + "\n"
                                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                                break
                    else:
                        code_list.append(this_name)
                        break
                if num_test_1 >= 3:
                    break
                if num2_makeing == 0:
                    numdas += 1

            if msg:
                return f"创建汇率方案及下属的汇率  创建汇率方案失败\n{msg}"

            if num2_makeing == 0:
                return "创建汇率方案及下属的汇率  创建汇率方案下的汇率 执行次数小于等于0，不执行"

            for code in code_list:
                list_id = self.QUERY_EXCHANGERATE(base_url, cookie, rateSchemeName=code)
                # print("1", list_id)
                if not len(list_id):
                    return f"创建汇率方案及下属的汇率  创建汇率方案下的汇率 未查询到编码为【{code}】的维度信息，请在对应服务器确认功能是否正常"
                rateDate = datetime.date.today()  # 获取「今天」
                saas = 0
                while saas < num2_makeing:
                    if rateDate.month == 12:  # 下一月
                        rateDate = rateDate.replace(year=rateDate.year + 1)
                        rateDate = rateDate.replace(month=rateDate.month - 11)
                    else:
                        rateDate = rateDate.replace(month=rateDate.month + 1)
                    # print("2", CURRENCY_CODE_list)
                    if len(CURRENCY_CODE_list):
                        for currcode in CURRENCY_CODE_list:
                            result = self.ADD_RATECON(base_url, cookie, list_id, rateDate=rateDate.strftime("%Y-%m-%d"),
                                                      scalerCurrencyCode=currcode)
                            if result.get("msg") != "success":
                                return f"创建汇率方案及下属的汇率  创建汇率方案下的汇率失败 已完成【{numdas}】次\n接口响应：{result}"
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            saas += 1
                            numdas += 1
                            if not saas < num2_makeing:
                                break
                    else:
                        result = self.ADD_RATECON(base_url, cookie, list_id, rateDate=rateDate.strftime("%Y-%m-%d"))
                        saas += 1
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                        if result.get("msg") != "success":
                            return f"创建汇率方案及下属的汇率  创建汇率方案下的汇率失败 已完成【{numdas}】次\n接口响应：{result}"
            totalNums = 1
            for n in [num_makeing, num2_makeing]:
                if n > 0:
                    totalNums *= n
                else:
                    break
            if numdas > totalNums:
                msg = f"汇率方案及下属的汇率创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"汇率方案及下属的汇率创建未完成，已完成【{numdas - 1}】条，未完成【{totalNums - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return str(e) + "\n" + msg

    # 创建账套-核算主体-成本中心
    def create_sob(self, **kwargs):
        """
        创建账套-核算主体-成本中心
        kwargs: namedflag每笔数据的标记；
        """
        msg = ''
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 3:
                    r_num.append(0)
                num_makeing, num2_makeing, num3_makeing = abs(int(r_num[0])), abs(int(r_num[1])), abs(
                    int(r_num[2]))  # 创建账套数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建账套-核算主体-成本中心  创建账套 获取执行次数异常"
            if num_makeing <= 0:
                return "创建账套-核算主体-成本中心  创建账套 执行次数必须大于0"
            # 获取币种列表
            result1 = self.FINDDATA(base_url, cookie,
                                    data='page=1&limit=50&orderField=&order=&lovKey=sysCurrencyMode.findNameAndCodeSingle&hasCount=N')
            # dictCode_list = self.GET_VALUE_FROM_JSON_DICT(result1, 'ID')  # 币种列表
            CURRENCY_CODE_list = self.GET_VALUE_FROM_JSON_DICT(result1, 'CURRENCY_CODE')  # 币种列表
            # 获取汇率方案exchangerate和本位币currencyCode
            concurrent_ = self.FINDDATA(base_url, cookie,
                                        data="page=1&limit=50&orderField=&order=&lovKey=sysExchangeRateMode.findNameAndCode&hasCount=N")
            list_BASIC_CURRENCY_ID = self.GET_VALUE_FROM_JSON_DICT(concurrent_, 'ID')
            list_BASIC_CURRENCY_CODE = self.GET_VALUE_FROM_JSON_DICT(concurrent_,
                                                                     'BASIC_CURRENCY_CODE')  # BASIC_CURRENCY_CODE
            ID_CODE_LIST = [list(t) for t in zip(list_BASIC_CURRENCY_ID, list_BASIC_CURRENCY_CODE)]
            # 获取科目体系coaaccountscheme
            result = self.FINDDATA(base_url, cookie,
                                   "page=1&limit=50&orderField=&order=&lovKey=sysCoaAccountSchemeMode.findNameAndCode&hasCount=N")
            list_coaaccountscheme = self.GET_VALUE_FROM_JSON_DICT(result, 'ID')
            numdas = 1
            sob_id_list = []
            for num_v in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                this_code = f"{namedFlag}sob{str(random_num)}"
                if namedFlag:
                    this_name = f"{namedFlag}账套名称{str(random_num)}"
                else:
                    this_name = f"账套名称{str(random_num)}"
                # 挑一个币种
                curr_code = CURRENCY_CODE_list[random.randint(0, len(CURRENCY_CODE_list) - 1)]
                # 挑一个汇率方案exchangerate和本位币
                saas = ID_CODE_LIST[random.randint(0, len(ID_CODE_LIST) - 1)]
                exchangerate = saas[0]  # 汇率方案
                currencyCode = saas[-1]  # 本位币
                # 挑一个科目体系
                coaaccountscheme = list_coaaccountscheme[random.randint(0, len(list_coaaccountscheme) - 1)]
                # ${coaaccountscheme}    ${exchangerate}    ${currencyId_this}
                num_this = 1
                while True:
                    result = self.ADD_SOB(base_url, cookie, this_code, this_name, coaaccountscheme, exchangerate,
                                          currencyCode=currencyCode, useCurrencyCode=curr_code)
                    if result.get('msg') == 'success':
                        sob_id = self.QUERY_SOB(base_url, cookie, sobCode=this_code).get('page').get('list')[0].get(
                            'id')
                        sob_id_list.append(sob_id)
                        break
                    else:
                        if num_this >= 3:
                            msg_ = result.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                            break
                        else:
                            num_this += 1
                            continue
                if num_this >= 3:
                    break

                if num2_makeing == 0:
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1

            if num2_makeing <= 0:
                return "创建账套-核算主体-成本中心  创建核算主体 执行次数小于等于0，不执行"

            # 新建核算主体
            for sobId in sob_id_list:
                for num in range(num2_makeing):
                    random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                    this_code = f"{namedFlag}fule{str(random_num)}"
                    if namedFlag:
                        this_name = f"{namedFlag}核算主体名称{str(random_num)}"
                    else:
                        this_name = f"核算主体名称{str(random_num)}"
                    #     ${result}    ZTCCLOUD.ADD_FULECC    ${ip}    ${cookie}    ${thisCode}    ${thisName}    ${sobId}
                    result = self.ADD_FULECC(base_url, cookie, this_code, this_name, sobId)
                    fuleccbzx_id = self.GET_DICT(result, 'id', code=this_code)
                    if num3_makeing == 0 and fuleccbzx_id:
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                    if not fuleccbzx_id:
                        continue
                    for numw in range(num3_makeing):
                        random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                        this_code = f"{namedFlag}fuleCC{str(random_num)}"
                        if namedFlag:
                            this_name = f"{namedFlag}成本中心名称{str(random_num)}"
                        else:
                            this_name = f"成本中心名称{str(random_num)}"
                        result = self.ADD_FULECC(base_url, cookie, this_code, this_name,
                                                 affiliatedFuleId=fuleccbzx_id, pid=fuleccbzx_id, fuType=1)
                        if result.get('msg') == 'success':
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            numdas += 1
            totalNums = 1
            for n in [num_makeing, num2_makeing, num3_makeing]:
                if n > 0:
                    totalNums *= n
                else:
                    break
            if numdas > totalNums:
                msg = f"账套-核算主体-成本中心创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"账套-核算主体-成本中心创建未完成，已完成【{numdas - 1}】条，未完成【{totalNums - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return msg + '\n' + str(e)

    # 创建公司账户和银行/票据科目配置
    def create_companybank(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建公司账户和银行/票据科目配置"
        msg = ''
        numdas = 1
        numdas_comp2bank = 0  # 银行&票据科目设置的数量
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 2:
                    r_num.append(0)
                num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建公司账户数和银行/票据科目配置数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建公司账户 获取执行次数异常"
            if num_makeing <= 0 or num_makeing < num2_makeing:
                return "创建公司账户 执行次数必须大于0且创建公司账户数不能小于银行/票据科目配置数量"
            # 查核算主体
            result = self.FINDDATA(base_url, cookie,
                                   'page=1&limit=50&orderField=&order=&lovKey=sysFuLeMode.findNameAndCode&hasCount=N')
            fuId_list = self.GET_VALUE_FROM_JSON_DICT(result, 'ID')  # 核算主体id
            sobId_list = self.GET_VALUE_FROM_JSON_DICT(result, 'SOB_ID')  # 账套id
            fuId_sobId = [list(t) for t in zip(fuId_list, sobId_list)]
            # 查开户行
            result = self.FINDDATA(base_url, cookie,
                                   'page=1&limit=50&orderField=&order=&lovKey=sysVendorMode.findBankAndGroupId&hasCount=N')
            subBankId_list = self.GET_VALUE_FROM_JSON_DICT(result, 'ID')
            bankTypeCode_list = self.GET_VALUE_FROM_JSON_DICT(result, 'BANK_TYPE_CODE')
            subBankId_bankTypeCode = [list(t) for t in zip(subBankId_list, bankTypeCode_list)]
            # 查币种
            result = self.FINDDATA(base_url, cookie,
                                   'page=1&limit=50&orderField=&order=&lovKey=sysCurrencyMode.findNameAndCodeMultiple&hasCount=N')
            currencyId_list = self.GET_VALUE_FROM_JSON_DICT(result, 'ID')
            for numas in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                this_code = f"{namedFlag}compBank{str(random_num)}"
                this_name = f"{namedFlag}公司账户{str(random_num)}"
                # 取用数据
                fuId, sobId = fuId_sobId[random.randint(0, len(fuId_sobId) - 1)]
                subBankId, bankTypeCode = subBankId_bankTypeCode[random.randint(0, len(subBankId_bankTypeCode) - 1)]
                currencyId = currencyId_list[random.randint(0, len(currencyId_list) - 1)]
                while True:
                    bankLevel = f'{random.randint(1000, int(1e+9) - 1)}'  # 优先级
                    result = self.ADD_COMPANYBANK(base_url, cookie, fuId=fuId, sobId=sobId, code=this_code,
                                                  subBank=subBankId,
                                                  bankTypeCode=bankTypeCode, currencyId=currencyId,
                                                  bankAccountName=this_name,
                                                  bankAccountNum=this_code, bankLevel=bankLevel)
                    if result.get("msg") != "优先级重复":
                        if result.get("msg") == "字段长度超过限制":
                            return "字段长度超出限制，请控制下长度[末尾特征标记]"
                        elif result.get('msg') == 'success':
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            if numdas_comp2bank < num2_makeing:  # 还没配置完
                                companyBankId = self.GET_DICT(self.QUERY_COMPANYBANK(base_url, cookie, code=this_code),
                                                              'id')
                                result2 = self.ADD_COMP2BANK(base_url, cookie, companyBankId=companyBankId,
                                                             bankAccountNum=this_code, leId=fuId, coaSchemeId=sobId,
                                                             BANK_ACCOUNT_NAME=this_name)
                                if result2.get('msg') == 'success':
                                    utils.set_cache(base_url, user_addr, "银行/票据科目配置")
                                    numdas_comp2bank += 1
                            if numdas >= num_makeing:
                                return f"{method_name}造数据完成"
                            numdas += 1
                        else:
                            msg_ = result.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                        break
            return f"{method_name}造数据的cross组合已用完，新增{numdas}条数据"
        except Exception as e:
            return msg + '\n' + str(e)

    # 结算方式
    def create_paymentmode(self, **kwargs):
        """
        创建结算方式
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建结算方式"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                num_makeing = int(kwargs.get("run_num"))
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建结算方式 获取执行次数异常"
            if num_makeing <= 0:
                return "创建结算方式 执行次数必须大于0"
            for numas in range(1, num_makeing + 1):
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                this_code = f"{namedFlag}paymentmode{str(random_num)}"
                this_name = f"{namedFlag}结算方式{str(random_num)}"
                num_ads = 0
                while True:
                    num_ads += 1
                    bankLevel = f'{random.randint(1, int(1e+5) - 1)}'  # 优先级
                    result = self.ADD_PAYMENTMODE(base_url, cookie, paymentSort=bankLevel, paymentCode=this_code,
                                                  paymentName_zh_CN=this_name)
                    if result.get("msg") != "优先级重复":
                        if result.get('msg') == 'success':
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            if numdas >= num_makeing:
                                return f"{method_name}造数据完成"
                            numdas += 1
                        else:
                            msg_ = result.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                        break
                    elif num_ads > 50:
                        return f"{method_name}造数据的cross组合已用完，新增{numdas}条数据"
            return f"{method_name}造数据的cross组合已用完，新增{numdas}条数据"
        except Exception as e:
            return msg + '\n' + str(e)

    # 创建税种税率
    def create_taxrate(self, **kwargs):
        """
        创建税种税率
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建税种税率"
        msg = ''
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                num_makeing = int(kwargs.get("run_num"))
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
            except:
                return "创建税种税率 获取执行次数异常"
            if num_makeing <= 0:
                return "创建税种税率 执行次数必须大于0"
            # 获取票据类型
            result1 = self.BILL_TYPE_INVOICE_TAXRATE(base_url, cookie)
            list_bill_type_invoice_code = self.GET_VALUE_FROM_JSON_DICT(result1, 'dictCode')  # 编码
            # 获取税率种类
            taxrate = self.TAX_RATE_TAXRATE(base_url, cookie)
            list_taxrate_dictCode = self.GET_VALUE_FROM_JSON_DICT(taxrate, 'dictCode')
            numdas = 1
            id_list = []
            for billTypeInvoice in list_bill_type_invoice_code:
                random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                this_code = f"{namedFlag}taxrate{str(random_num)}"
                result = self.ADD_TAXRATE(base_url, cookie, this_code, billTypeInvoice=billTypeInvoice, pid='0')
                if result.get('msg') == 'success':
                    id_this = self.QUERY_TAXRATE(base_url, cookie, taxCode=this_code)
                    id_list.append([id_this, billTypeInvoice])
                    for taxrate in list_taxrate_dictCode:
                        random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                        this_code = f"{namedFlag}taxrate{str(random_num)}"
                        result = self.ADD_TAXRATE(base_url, cookie, this_code, billTypeInvoice=billTypeInvoice,
                                                  pid=id_this, taxValue=taxrate)
                        if result.get('msg') == 'success':
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            if numdas >= num_makeing:
                                return f"{method_name}造数据完成"

                            numdas += 1
                        else:
                            msg_ = result.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                else:
                    msg_ = result.get('msg')
                    if msg_:
                        msg += msg_ + '\n'
            return f"{method_name}造数据的cross组合已用完，新增{numdas}条数据"
        except Exception as e:
            return msg + '\n' + str(e)

    # 业务类型
    def create_category(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建业务类型 业务大类&业务小类"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 2:
                    r_num.append(0)
                num_makeing, num2_makeing = abs(int(r_num[0])), abs(int(r_num[1]))  # 创建业务大类数,业务小类数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"
            for numas in range(1, num_makeing + 1):
                random_num = self.random_character(char_type="str", length="8")
                this_code = f"{namedFlag}{str(random_num)}"
                this_name = f"{namedFlag}业务类型{str(random_num)}"
                result = self.ADD_CATEGORY(base_url, cookie, code=this_code, name_zh_CN=this_name, pid='0')
                if result.get("msg") == "字段长度超过限制":
                    return f"{method_name} 字段长度超出限制，请控制下长度[末尾特征标记]"
                if result.get('msg') == 'success':
                    if num2_makeing <= 0:
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        numdas += 1
                    pid = self.GET_DICT(result, 'id')
                    # 新建业务小类
                    for small in range(1, num2_makeing + 1):
                        random_num = self.random_character(char_type="str", length="8")
                        this_code = f"{namedFlag}{str(random_num)}"
                        this_name = f"{namedFlag}业务小类{str(random_num)}"
                        result = self.ADD_CATEGORY(base_url, cookie, code=this_code, name_zh_CN=this_name, pid=pid,
                                                   type=1)
                        if result.get('msg') == 'success':
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            numdas += 1
                        else:
                            msg_ = result.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                else:
                    msg_ = result.get('msg')
                    if msg_:
                        msg += msg_ + '\n'
            if numdas > num_makeing * (num2_makeing or 1):
                msg = f"{method_name} 创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name} 创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing * (num2_makeing or 1) - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return msg + '\n' + str(e)

    # 会计科目配置
    def create_acctsubconf(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "会计科目相关配置"
        msg = ''
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 会计科目相关配置数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"
            # 业务科目配置：
            # 查业务类型大小类所有id
            result = self.QUERY_CATEGORY_TREE(base_url, cookie)
            caregory_list = set(self.GET_VALUE_FROM_JSON_DICT(result, 'id'))
            # 查业务科目类型所有id
            result = self.QUERY_BIZ_ACCOUNT_TYPE(base_url, cookie)
            accountType_list = self.GET_VALUE_FROM_JSON_DICT(result, 'dictCode')

            # 求出要建立多少账套
            num_yewu_kmpz = int(num_makeing / (len(caregory_list) * len(accountType_list))) + 1
            # 税务科目配置：
            # 查税种税率所有id
            result = self.QUERY_TAXRATE_TREE(base_url, cookie)
            taxrate_list = set(self.GET_VALUE_FROM_JSON_DICT(result, 'id'))
            # 进项销项
            accountType2_list = ["ENTRY", "SALES"]
            # 求出要建立多少账套
            num_shuizhong_kmpz = int(num_makeing / (len(taxrate_list) * len(accountType2_list))) + 1
            # 结算科目配置：
            # 查结算方式50条所有id，和结算方式总数
            result = self.QUERY_PAYMENTMODE(base_url, cookie)
            paymentmode_list = self.GET_VALUE_FROM_JSON_DICT(result, 'id')
            transferFundFlag_list = self.GET_VALUE_FROM_JSON_DICT(result, 'transferFundFlag')
            paymentmode_len = self.GET_DICT(result, 'totalCount')
            # 求出要建立多少账套
            num_jiesuan_kmpz = int(num_makeing / int(paymentmode_len)) + 1
            num_sob_makeing = max([num_yewu_kmpz, num_shuizhong_kmpz, num_jiesuan_kmpz])
            sob_id_list = []  # 存放账套id
            coaSchemeId_list = []  # 存放科目体系id

            if num_sob_makeing > 0:
                # 获取币种列表
                result1 = self.FINDDATA(base_url, cookie,
                                        data='page=1&limit=50&orderField=&order=&lovKey=sysCurrencyMode.findNameAndCodeSingle&hasCount=N')
                CURRENCY_CODE_list = self.GET_VALUE_FROM_JSON_DICT(result1, 'CURRENCY_CODE')  # 币种列表
                # 获取汇率方案exchangerate和本位币currencyCode
                concurrent_ = self.FINDDATA(base_url, cookie,
                                            data="page=1&limit=50&orderField=&order=&lovKey=sysExchangeRateMode.findNameAndCode&hasCount=N")
                list_BASIC_CURRENCY_ID = self.GET_VALUE_FROM_JSON_DICT(concurrent_, 'ID')
                list_BASIC_CURRENCY_CODE = self.GET_VALUE_FROM_JSON_DICT(concurrent_, 'BASIC_CURRENCY_CODE')
                ID_CODE_LIST = [list(t) for t in zip(list_BASIC_CURRENCY_ID, list_BASIC_CURRENCY_CODE)]
                # 获取科目体系coaaccountscheme
                result = self.FINDDATA(base_url, cookie,
                                       "page=1&limit=1000&orderField=&order=&lovKey=sysCoaAccountSchemeMode.findNameAndCode&hasCount=N")
                list_coaaccountscheme = self.GET_VALUE_FROM_JSON_DICT(result, 'ID')
                for num_v in range(1, num_sob_makeing + 1):
                    random_num = f'{random.randint(int(1e+7), int(1e+8))}'  # 随机数8位
                    this_code = f"{namedFlag}sob{str(random_num)}"
                    this_name = f"{namedFlag}账套名称{str(random_num)}"
                    # 挑一个币种
                    curr_code = random.choice(CURRENCY_CODE_list)
                    # 挑一个汇率方案exchangerate和本位币
                    saas = random.choice(ID_CODE_LIST)
                    exchangerate = saas[0]  # 汇率方案
                    currencyCode = saas[-1]  # 本位币
                    # 挑一个科目体系
                    coaaccountscheme = random.choice(list_coaaccountscheme)
                    if not self.QUERY_COA(base_url, cookie, accountSchemeId=coaaccountscheme).get('page').get(
                            'totalCount'):
                        this_Coacode = f"{namedFlag}Coa{str(random_num)}"
                        this_Coaname = f"{namedFlag}会计科目名称{str(random_num)}"
                        self.ADD_COA(base_url, cookie, this_Coacode, this_Coaname, coaaccountscheme)
                    num_this = 1
                    while True:
                        result = self.ADD_SOB(base_url, cookie, this_code, this_name, coaaccountscheme, exchangerate,
                                              currencyCode=currencyCode, useCurrencyCode=curr_code)
                        if result.get("msg") == "字段长度超过限制":
                            return "字段长度超出限制，请控制下长度[末尾特征标记]"
                        if result.get('msg') == 'success':
                            result3 = self.QUERY_SOB(base_url, cookie, sobCode=this_code)
                            sob_id = result3.get('page').get('list')[0].get('id')
                            coaSchemeId = result3.get('page').get('list')[0].get('coaSchemeId')
                            coaSchemeId_list.append(coaSchemeId)
                            sob_id_list.append(sob_id)
                            break
                        else:
                            if num_this >= 3:
                                msg_ = result.get('msg')
                                if msg_:
                                    msg += msg_ + '\n'
                                break
                            else:
                                num_this += 1
                                continue
                    if num_this >= 3:
                        break
            sob_list = [list(t) for t in zip(sob_id_list, coaSchemeId_list)]

            # 业务科目配置
            try:
                t8 = threading.Thread(target=self.ADD_BIZ2ACCOUNT, args=(base_url, cookie, sob_list, caregory_list,
                                                                         accountType_list, num_makeing),
                                      kwargs={"user_addr": user_addr})
                t8.daemon = True
                t8.start()
            except Exception as error:
                msg += f"业务科目配置 执行异常：{error}\n"
            # self.ADD_BIZ2ACCOUNT(base_url, cookie, sob_list=sob_list, bizCategoryId_list=caregory_list,
            #                                        accountType_list=accountType_list, goal=num_makeing)

            # 税务科目配置
            try:
                t9 = threading.Thread(target=self.ADD_TAXRATEC, args=(base_url, cookie, sob_list, taxrate_list,
                                                                      accountType_list, num_makeing),
                                      kwargs={"user_addr": user_addr})
                t9.daemon = True
                t9.start()
            except Exception as error:
                msg += f"税务科目配置 执行异常：{error}\n"
            # 结算科目配置
            try:
                payment_list = [list(t) for t in zip(paymentmode_list, transferFundFlag_list)]
                t10 = threading.Thread(target=self.ADD_PAYMODEACCT, args=(base_url, cookie, sob_list, payment_list,
                                                                          num_makeing), kwargs={"user_addr": user_addr})
                t10.daemon = True
                t10.start()
            except Exception as error:
                msg += f"结算科目配置 执行异常：{error}\n"
        except Exception as e:
            return msg + '\n' + str(e)

    # 凭证配置(会计结构建立、辅助核算建立)
    def create_acctstructures(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "凭证配置-会计结构建立、辅助核算建立"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建业务大类数,业务小类数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 查账套id列表
            result23 = self.QUERY_SOB(base_url, cookie, validityFlag='0')

            sobId_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'id')

            if not len(sobId_list):
                sobId_list = self.CREATE_SOBS(base_url, cookie, 2, namedFlag)
            for numas in range(1, num_makeing + 1):
                random_num = self.random_character(char_type="str", length="8")
                this_code = f"{namedFlag}kjjg_{str(random_num)}"
                this_name = f"{namedFlag}会计结构{str(random_num)}"
                result = self.ADD_ACCOUNTSTRUCTURES(base_url, cookie, structureCode=this_code, structureName=this_name,
                                                    namedFlag=namedFlag)
                if result.get("msg") == "字段长度超过限制":
                    return "字段长度超出限制，请控制下长度[末尾特征标记]"
                if result.get('msg') == 'success':
                    # utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1
                    secondarySegmentId = self.GET_DICT(result, 'id')  # 会计结构id
                    # 关联账套
                    sob_choiced = random.choice(sobId_list)
                    self.LINK_SOB_SECONDARYSEGMENT(base_url, cookie, sobId=sob_choiced,
                                                   secondarySegment=secondarySegmentId)
                    # 新增辅助核算
                    this_code2 = f"{namedFlag}fzhs_{str(random_num)}"
                    this_name2 = f"{namedFlag}辅助核算{str(random_num)}"
                    result33 = self.ADD_STRUCTURESGROUP(base_url, cookie, sobId=sob_choiced,
                                                        structureGroupName=this_name2, structureGroupCode=this_code2)
                    if result33.get('msg') == 'success':
                        utils.set_cache(base_url, user_addr, utils.get_func_name())
                        result45 = self.QUERY_STRUCTURESGROUP(base_url, cookie, structureGroupCode=this_code2)
                        structureGroupId = self.GET_DICT(result45, 'id')
                        ids = self.GET_DICT(
                            self.FINDDATA(base_url, cookie, f'page=1&limit=20&orderField=&order=&lovKey='
                                                            f'sysStructuresGroup.findStructureDetails&SOB_ID={sob_choiced}&hasCount=N'),
                            'ID')
                        self.ADD_STRUCTCONF(base_url, cookie, id=structureGroupId, ids=ids)
                    else:
                        msg_ = result.get('msg')
                        if msg_:
                            msg += msg_ + '\n'
                else:
                    msg_ = result.get('msg')
                    if msg_:
                        msg += msg_ + '\n'
            if numdas > num_makeing:
                msg = f"{method_name} 创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name} 创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            return msg + '\n' + str(e)

    # SAP相关配置(特殊总账类型、特殊总账标识)
    def create_specialgl(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "SAP相关配置-特殊总账类型、特殊总账标识新增"
        msg = ''
        numdas_1, numdas_2 = 1, 1

        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 会计科目相关配置数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 查账套id列表
            result23 = self.QUERY_SOB(base_url, cookie, validityFlag='0', limit='20')
            len1212th = len(result23.get('page').get('list'))
            if len1212th < 20:
                self.CREATE_SOBS(base_url, cookie, 20 - len1212th, namedFlag)
            result23 = self.QUERY_SOB(base_url, cookie, validityFlag='0', limit='20')
            sobId_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'id')
            sobCode_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'sobCode')
            sobName_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'name')
            coaSchemeId_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'coaSchemeId')

            sob_list = [list(k) for k in zip(sobId_list, sobCode_list, sobName_list, coaSchemeId_list)]
            accountType_list = ['A', 'D', 'K', 'S']

            for numas in range(1, num_makeing + 1):
                for accountType in accountType_list:
                    random_num = self.random_character(char_type="str", length="8")
                    this_code = f"{namedFlag}type_{str(random_num)}"
                    this_name = f"{namedFlag}总账类型{str(random_num)}"
                    sob = random.choice(sob_list)
                    result = self.ADD_SPECIALGLTYPE(base_url, cookie, sobId=sob[0], sobCode=sob[1],
                                                    sobName=sob[2], accountType=accountType, glCode=this_code,
                                                    glName=this_name)
                    if result.get("msg") == "字段长度超过限制":
                        return "字段长度超出限制，请控制下长度[末尾特征标记]"
                    if result.get('msg') == 'success':
                        # list_base_num_more[6] += 1
                        numdas_1 += 1
                        # 科目
                        accountId_list = self.GET_VALUE_FROM_JSON_DICT(self.FINDDATA(base_url, cookie,
                                                                                     f'page=1&limit=50&orderField=&order=&lovKey=sysCoaAccountErpMode.'
                                                                                     f'findNameAndCode&HIERARCHY=0&ACCOUNT_SCHEME_ID={sob[3]}&hasCount=N'),
                                                                       'ID')
                        result33 = self.ADD_SAPSGL(base_url, cookie, sobCode=sob[1], coaAccountType=accountType,
                                                   sgl=this_code,
                                                   controlAccountId=random.choice(accountId_list),
                                                   targetAccountId=random.choice(accountId_list),
                                                   coaSchemeId=sob[3], sglName=this_name, sobName=sob[2])

                        if result33.get('msg') == 'success':
                            # list_base_num_more[7] += 1
                            utils.set_cache(base_url, user_addr, utils.get_func_name())
                            numdas_2 += 1
                            if numdas_1 > num_makeing and numdas_2 > num_makeing:
                                msg += f"{method_name} 创建完成，共【{numdas_2 - 1}】条"
                        else:
                            msg_ = result33.get('msg')
                            if msg_:
                                msg += msg_ + '\n'
                    else:
                        msg_ = result.get('msg')
                        if msg_:
                            msg += msg_ + '\n'
            if numdas_1 > num_makeing and numdas_2 > num_makeing:
                msg = f"{method_name} 创建完成，共【{numdas_2 - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name} 创建未完成，已完成【{numdas_2 - 1}】条，未完成【{num_makeing - numdas_2 + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg
        except Exception as e:
            msg += '\n' + str(e)
            return msg

    # SAP相关配置(记账代码)
    def create_postingkey(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "记账代码"
        msg = ''
        numdas = 1
        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                num_makeing = abs(int(r_num[0]))  # 创建业务大类数,业务小类数
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"

            # 查账套id列表
            result23 = self.QUERY_SOB(base_url, cookie, validityFlag='0', limit='20')
            len1212th = len(result23.get('page').get('list'))
            if len1212th < 20:
                self.CREATE_SOBS(base_url, cookie, 20 - len1212th, namedFlag)
            result23 = self.QUERY_SOB(base_url, cookie, validityFlag='0', limit='20')
            sobId_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'id')
            sobCode_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'sobCode')
            sobName_list = self.GET_VALUE_FROM_JSON_DICT(result23, 'name')

            sob_list = [list(k) for k in zip(sobId_list, sobCode_list, sobName_list)]

            for numas in range(1, num_makeing + 1):
                random_num = self.random_character(char_type="str", length="6")
                this_code = f"{namedFlag}unavailable_{str(random_num)}"
                this_name = f"{namedFlag}不可用的记账代码{str(random_num)}"
                sob = random.choice(sob_list)
                result = self.ADD_POSTINGKEY(base_url, cookie, sobId=sob[0], sobCode=sob[1],
                                             sobName=sob[2], postingKeyCode=this_code, postingKeyName=this_name)
                if result.get("msg") == "字段长度超过限制":
                    return "字段长度超出限制，请控制下长度[末尾特征标记]"
                if result.get('msg') == 'success':
                    # list_base_num[15] += 1
                    utils.set_cache(base_url, user_addr, utils.get_func_name())
                    numdas += 1

                else:
                    msg_ = result.get('msg')
                    if msg_:
                        msg += msg_ + '\n'
            if numdas > num_makeing:
                msg = f"{method_name} 创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name} 创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            return msg

        except Exception as e:
            msg += '\n' + str(e)
            return msg

    # 创建流程模板
    def create_fmc_template(self, **kwargs):
        """
        创建流程模板
        kwargs: namedflag每笔数据的标记；
        """
        try:
            cookie = kwargs.get("cookie")
            base_url = kwargs.get("server_addr")
            user_addr = kwargs.get("user_addr")
            num_makeing = int(kwargs.get('run_num') if kwargs.get('run_num') else 0)
            namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""
        except:
            return "创建流程模板  获取执行次数异常"
        if num_makeing <= 0:
            return "创建流程模板  执行次数必须大于0"
        resp = self.QUERY_FMC_TEMPLATE_CATEGORY(base_url, cookie)
        fscTemplateCategoryIdList = self.GET_VALUE_FROM_JSON_DICT(resp, "id")
        for i in fscTemplateCategoryIdList:
            if len(i) <= 1:
                fscTemplateCategoryIdList.remove(i)
                break
        # 选择所属公司
        resp = self.QUERY_FMC_TEMPLATE_COMPANY(base_url, cookie)
        rootCompanyId = random.choice(resp.get("tree")).get("id")
        resp = self.QUERY_FMC_TEMPLATE_COMPANY(base_url, cookie, **{"pid": rootCompanyId})
        companyIds = self.GET_VALUE_FROM_JSON_DICT(resp, "id")
        numdas = 1
        for num_v in range(1, num_makeing + 1):
            random_num = f'{random.randint(int(1e+9), int(1e+10))}'  # 随机数10位
            templateCode = f"{namedFlag}{str(random_num)}"
            templateName = f"{namedFlag}模板名称{str(random_num)}"
            categoryId = random.choice(fscTemplateCategoryIdList)
            companyId = random.choice(companyIds)
            # processId = random.choice(companyIds)
            # 新增流程模板
            result = self.ADD_FMC_TEMPLATE(base_url, cookie, **{
                "templateCode": templateCode,
                "templateName": templateName,
                "categoryId": categoryId,
                "companyId": companyId
            })
            if result.get("msg") != "success":
                return f"创建流程模板  已完成【{numdas}】次\n接口响应：{result}"

            # 配置流程模板
            self.DEPLOY_FMC_TEMPLATE(base_url, cookie, **{"templateName": templateName, "categoryId": categoryId})
            utils.set_cache(base_url, user_addr, utils.get_func_name())
            numdas += 1
        if numdas >= num_makeing:
            msg = f"创建流程模板已完成，共【{numdas - 1}】条"
        else:
            dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
            msg = f"创建流程模板，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
        return msg

    # 创建单据模板
    def create_boe_template(self, **kwargs):
        """
        添加单据模板
        kwargs: namedflag每笔数据的标记；
        """
        try:
            cookie = kwargs.get("cookie")
            base_url = kwargs.get("server_addr")
            user_addr = kwargs.get("user_addr")
            num_makeing = int(kwargs.get('run_num') if kwargs.get('run_num') else 0)
            namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""
        except:
            return "新增单据模板  获取执行次数异常"
        if num_makeing <= 0:
            return "新增单据模板  执行次数必须大于0"
        resp = self.QUERY_BOE_TEMPLATE(base_url, cookie)
        boeTemplateList = resp.get("page").get("list")
        if not boeTemplateList:
            return f"新增单据模板 查询单据模板失败\n接口响应：{resp.text}"
        numdas = 1
        for num_v in range(1, num_makeing + 1):
            boeTemplate = random.choice(boeTemplateList)
            random_num = f'{random.randint(int(1e+3), int(1e+5))}'  # 随机数10位
            boeTypeCode = "_".join(boeTemplate["boeTypeCode"].split("_")[1:3])
            boeTemplate["boeTemplateId"] = boeTemplate["id"]
            boeTemplate["boeTemplateName"] = f'{namedFlag}{boeTemplate["boeTypeName"]}_{random_num}'
            boeTemplate["boeTemplateCode"] = f'{namedFlag}{boeTypeCode}_{random_num}'
            boeTemplate["remark"] = f'This is {boeTemplate["boeTypeName"]} remark...'
            fromSystem = boeTemplate.get("fromSystem")

            # 新增单据模板
            result = self.ADD_BOE_TEMPLATE(base_url, cookie, **boeTemplate)
            if result.get("msg") != "success":
                return f"新增单据模板失败\n接口响应：{result}"
            # 发布单据模板
            result = self.DEPLOY_BOE_TEMPLATE(base_url, cookie,
                                              **{"boeTemplateCode": boeTemplate.get("boeTemplateCode")})
            if result[0].get("msg") != "success":
                return f"发布单据模板失败\n接口响应：{result}"
            # 配置业务类型
            boeTemplateId = result[1]
            result = self.CONFIG_BOE_TEMPLATE_CATEGORY(base_url, cookie, **{"boeTemplateId": boeTemplateId})
            if result.get("msg") != "success":
                return f"配置单据模板失败 配置业务类型失败\n接口响应：{result}"

            # 配置流程模板引用
            result = self.CONFIG_BOE_TEMPLATE_FMC(base_url, cookie,
                                                  **{"boeTypeId": boeTemplateId, "fromSystem": fromSystem})
            if result.get("msg") != "success":
                return f"配置单据模板失败 配置流程模板引用失败\n接口响应：{result}"

            # 配置账户分配
            result = self.CONFIG_BOE_TEMPLATE_ACCOUNT(base_url, cookie, **{"boeTypeId": boeTemplateId})
            if result.get("msg") != "success":
                return f"配置单据模板失败 配置账户分配失败\n接口响应：{result}"

            # 配置结算方式分配
            result = self.CONFIG_BOE_TEMPLATE_PAYMENT_METHODS(base_url, cookie, **{"boeTypeId": boeTemplateId})
            if result.get("msg") != "success":
                return f"配置单据模板失败 配置结算方式分配\n接口响应：{result}"

            # 配置凭证类型
            if boeTemplate.get("isGenVoucher") == "0":
                result = self.CONFIG_BOE_TEMPLATE_VOUCHER_TYPE(base_url, cookie, **{"boeTypeId": boeTemplateId})
                if result.get("msg") != "success":
                    return f"配置单据模板失败 配置凭证类型失败\n接口响应：{result}"
            utils.set_cache(base_url, user_addr, utils.get_func_name())
            numdas += 1
        if numdas >= num_makeing:
            msg = f"配置单据模板完成，共【{numdas - 1}】条"
        else:
            dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
            msg = f"配置单据模板，已完成【{numdas - 1}】条，未完成【{num_makeing - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
        return msg


class LCDUCK(ZTCCLOUD):

    # 1、流水(收款、收票、扣款)

    # 创建票据台账(应收、应付、支票)
    def create_ldgbillaccount(self, **kwargs):
        """
        kwargs: namedflag每笔数据的标记；
        """
        method_name = "创建票据台账(应收、应付、支票)"
        msg = ''
        numdas, numdas2, numdas3 = 1, 1, 1

        try:
            try:
                cookie = kwargs.get("cookie")
                base_url = kwargs.get("server_addr")
                user_addr = kwargs.get("user_addr")
                r_num = kwargs.get("run_num").strip("^").split("^")
                while len(r_num) < 4:
                    r_num.append(0)
                # 创建应收、应付、支票票据台账数
                num_makeing, num2_makeing, num3_makeing = abs(int(r_num[0])), abs(int(r_num[1])), abs(
                    int(r_num[2]))  # 应收、应付、支票
                namedFlag = f"{kwargs.get('named_pre')}" if kwargs.get('named_pre') else ""  # 每笔数据的标记
                if num_makeing <= 0:
                    return f"{method_name} 字段值异常，造数数量需为正整数"
            except:
                return f"{method_name} 字段值异常，造数数量需为正整数"
            # 获取核算主体&归属账户
            result09 = self.QUERY_COMPANYBANK(base_url, cookie, limit='100')
            leId_accountId_list = self.GET_VALUE_FROM_JSON_DICT(result09,
                                                                ['fuId', 'id', 'bankAccountNum', 'bankHeadOffice'])
            # 往来方
            VendorAndClientId_list = self.GET_VALUE_FROM_JSON_DICT(self.FINDDATA(base_url, cookie,
                                                                                 'page=1&limit=100&orderField=&order=&lovKey=fscBillAccount.findVendorAndClient'),
                                                                   'ID')
            # 经办人 # 签收人
            operatorId_list = self.GET_VALUE_FROM_JSON_DICT(
                self.FINDDATA(base_url, cookie, 'page=1&limit=100&orderField'
                                                '=&order=&lovKey=fscBillAccount.findEmpAndPostDept&PRIMARY_POST=0',
                              url='/sys/common/lov/findDatas'), 'ID')

            for numas in range(1, num_makeing + 1):
                random_num = self.random_character(char_type="str", length="8")
                this_code = f"{namedFlag}{str(random_num)}"
                # this_name = f"{namedFlag}应收票据台账{str(random_num)}"
                result = self.ADD_LDG_BILL_ACCOUNT(base_url, cookie,
                                                   leId_accountId_list=random.choice(leId_accountId_list),
                                                   postalOrderCode=this_code,
                                                   preEndorseId=random.choice(VendorAndClientId_list),
                                                   operatorId=random.choice(operatorId_list),
                                                   signEmpId=random.choice(operatorId_list))
                if result.get("msg") == "字段长度超过限制":
                    return f"{method_name} 字段长度超出限制，请控制下长度[末尾特征标记]"
                if result.get('msg') == 'success':
                    if num2_makeing <= 0:
                        utils.set_cache(base_url, user_addr, "应收汇票")
                        numdas += 1
                else:
                    msg_ = result.get('msg')
                    if msg_:
                        msg += msg_ + '\n'
            if numdas > num_makeing * (num2_makeing or 1):
                msg = f"{method_name} 创建完成，共【{numdas - 1}】条"
            else:
                dbUtils.write_data_to_db(kwargs.get("task_id"), user_addr, base_url)
                msg = f"{method_name} 创建未完成，已完成【{numdas - 1}】条，未完成【{num_makeing * (num2_makeing or 1) - numdas + 1}】条，原因：自己看【{base_url}】服务器日志"
            print(f'>>>{msg}')
            return msg
        except Exception as e:
            return msg + '\n' + str(e)
    # 2、票据台账(应收、应付、支票)
    # 3、发票(电子专票、电子普票、其他纸质票)
    # 4、合同(销售合同、采购合同)
    # 5、预算模板
